import { Component, DestroyRef, inject, OnInit } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { ShequService } from '../services/shequ.service';
import { SheQu } from '../models/shequ.model';
import { MyPaginatorComponent } from '../my-paginator/my-paginator.component';
import { DeferLoadTableComponent } from "./defer-load-table/defer-load-table.component";

@Component({
  selector: 'app-shequ',
  imports: [RouterLink, MyPaginatorComponent, DeferLoadTableComponent],
  templateUrl: './shequ.component.html',
  styleUrl:'./shequ.component.css',
})
export class SheQuComponent implements OnInit {
  private router = inject(Router);
  private destroyRef = inject(DestroyRef);
  private shequService = inject(ShequService);
  //如果不启动后端，从假数据中加载
  dataSource: SheQu[] = [];

  ngOnInit(): void {
    /*     const subscription = this.shequService.getAllSheQu().subscribe({
          error: (error: Error) => console.log(error.message),
          complete: () => { this.dataSource.data = this.shequService.allSheQu(); }
        })
        this.destroyRef.onDestroy(() => subscription.unsubscribe()); */
    this.dataSource = this.shequService.allSheQu();
  }


  editBtnClick(shequ: SheQu): void {
    this.router.navigate(['/shequ', 'edit', shequ.sheQuID]);
  }

  deleteBtnClick(shequ: SheQu): void {
    const subscription = this.shequService.deleteSheQu(shequ.sheQuID!).subscribe({
      next: () => {
        this.dataSource = this.dataSource.filter(item => item.sheQuID !== shequ.sheQuID);
      },
      error: (error: Error) => console.log(error.message),
      complete: () => { }
    });
    this.destroyRef.onDestroy(() => subscription.unsubscribe());
  }
}
